package auth.web;


import auth.exception.GulimallExceptionControllerAdvice;
import auth.service.feign.MemberFeignService;
import com.alibaba.fastjson.TypeReference;
import com.wu.common.entity.member.MemberEntity;
import com.wu.common.exception.BizCodeEnum;
import com.wu.common.utils.R;
import com.wu.common.vo.auth.UserLoginVo;
import com.wu.common.vo.auth.UserRegisterVo;
import com.wu.common.vo.member.MemberUserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import auth.service.feign.ThirdPartFeignService;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.naming.Binding;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: gumo-mall
 * @author: wuyunpeng
 * @create: 2025-04-07 15:20
 */
@Controller
public class LoginController {

    @Resource
    private ThirdPartFeignService thirdPartFeignService;

    @Resource
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //验证码防刷
        String key = "sms:code:" + phone;
        String code = stringRedisTemplate.opsForValue().get(key);
        if (code != null && code.length() > 0) {
            long l = Long.parseLong(code.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        //保存验证码
        Double v = Math.random() * 9000 + 1000;
        Long l = v.longValue();
        code = l.toString();
        stringRedisTemplate.opsForValue().set(key, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        return thirdPartFeignService.sendCode(phone, code);
    }


    @PostMapping("/register")
    public String register(UserRegisterVo userRegisterVo, BindingResult bindingResult, RedirectAttributes re) {
        Map<String, Object> errors = null;
        if (bindingResult.hasErrors()) {
            errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getRejectedValue));
            re.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        String key = "sms:code:" + userRegisterVo.getPhone();
        String code = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(code) || !userRegisterVo.getCode().equals(code.split("_")[0])) {
            errors = new HashMap<>();
            errors.put("code", "验证码错误");
            re.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        R r = memberFeignService.register(userRegisterVo);
        if (r.getCode() != 0) {
            errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            re.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        } else {
            stringRedisTemplate.delete(key);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes attributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if (r.getCode() != 0) {
            Map<String, Object> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        } else {
            session.setAttribute("loginUser", r.getData("data", new TypeReference<MemberEntity>() {
            }));
            return "redirect:http://gulimall.com";
        }
    }
}